package com.apikey.auth.controller;

import com.apikey.auth.entity.Application;
import com.apikey.auth.service.ApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * API Key申请控制器
 * 提供申请相关的REST API接口
 *
 * @author API Key Framework
 * @version 1.0
 */
@RestController
@RequestMapping("/api/applications")
@CrossOrigin(originPatterns = {"http://localhost:*", "http://127.0.0.1:*", "https://localhost:*", "https://127.0.0.1:*"}, allowCredentials = "true")
public class ApplicationController {

    @Autowired
    private ApplicationService applicationService;

    /**
     * 提交API Key申请
     *
     * @param request 申请请求
     * @return 申请结果
     */
    @PostMapping("/submit")
    public ResponseEntity<Map<String, Object>> submitApplication(@RequestBody ApplicationRequest request) {
        Application application = applicationService.submitApplication(
                request.getPhoneNumber(),
                request.getVerifyPassword(),
                request.getFingerprint(),
                request.getRemark()
        );
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "申请提交成功");
        response.put("data", convertToResponse(application));
        return ResponseEntity.ok(response);
    }

    /**
     * 根据手机号查询申请状态
     *
     * @param phoneNumber    手机号
     * @param verifyPassword 验证密码（可选）
     * @return 申请状态列表
     */
    @GetMapping("/query")
    public ResponseEntity<Map<String, Object>> queryApplication(
            @RequestParam String phoneNumber,
            @RequestParam(required = false) String verifyPassword) {
        
        Map<String, Object> response = new HashMap<>();
        
        // 使用统一的查询方法，返回申请记录列表
        List<Application> applications = applicationService.queryApplicationByPhone(phoneNumber, verifyPassword);
        
        if (!applications.isEmpty()) {
            response.put("success", true);
            response.put("message", "查询成功，找到 " + applications.size() + " 条记录");
            response.put("data", applications.stream()
                    .map(this::convertToResponse)
                    .collect(java.util.stream.Collectors.toList()));
        } else {
            response.put("success", false);
            response.put("message", "未找到相关申请记录");
            response.put("data", new java.util.ArrayList<>());
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 根据手机号查询申请状态 (POST方式)
     *
     * @param request 查询请求
     * @return 申请状态列表
     */
    @PostMapping("/query/phone")
    public ResponseEntity<Map<String, Object>> queryApplicationByPhone(@RequestBody QueryRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        // 使用统一的查询方法，返回申请记录列表
        List<Application> applications = applicationService.queryApplicationByPhone(
                request.getPhoneNumber(), request.getVerifyPassword());
        
        if (!applications.isEmpty()) {
            response.put("success", true);
            response.put("message", "查询成功，找到 " + applications.size() + " 条记录");
            response.put("data", applications.stream()
                    .map(this::convertToResponse)
                    .collect(java.util.stream.Collectors.toList()));
        } else {
            response.put("success", false);
            response.put("message", "未找到相关申请记录");
            response.put("data", new java.util.ArrayList<>());
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 根据浏览器指纹查询申请状态
     *
     * @param fingerprint 浏览器指纹
     * @return 申请状态列表
     */
    @GetMapping("/query-by-fingerprint")
    public ResponseEntity<Map<String, Object>> queryApplicationsByFingerprint(@RequestParam String fingerprint) {
        List<Application> applications = applicationService.queryApplicationsByFingerprint(fingerprint);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "查询成功");
        response.put("data", applications.stream().map(this::convertToResponse).collect(java.util.stream.Collectors.toList()));
        return ResponseEntity.ok(response);
    }

    /**
     * 根据浏览器指纹查询申请状态 (POST方式)
     *
     * @param request 查询请求
     * @return 申请状态列表
     */
    @PostMapping("/query/fingerprint")
    public ResponseEntity<Map<String, Object>> queryApplicationsByFingerprintPost(@RequestBody QueryRequest request) {
        List<Application> applications = applicationService.queryApplicationsByFingerprint(request.getFingerprint());
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "查询成功");
        response.put("data", applications.stream().map(this::convertToResponse).collect(java.util.stream.Collectors.toList()));
        return ResponseEntity.ok(response);
    }

    /**
     * 获取申请详情
     *
     * @param id 申请ID
     * @return 申请详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getApplication(@PathVariable Long id) {
        Optional<Application> applicationOpt = applicationService.findById(id);
        
        Map<String, Object> response = new HashMap<>();
        if (applicationOpt.isPresent()) {
            response.put("success", true);
            response.put("message", "查询成功");
            response.put("data", convertToResponse(applicationOpt.get()));
        } else {
            response.put("success", false);
            response.put("message", "申请记录不存在");
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取申请统计信息
     *
     * @return 统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getStatistics() {
        Map<Application.Status, Long> statistics = applicationService.getStatusStatistics();
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "查询成功");
        response.put("data", statistics);
        return ResponseEntity.ok(response);
    }

    /**
     * 获取最近申请记录
     *
     * @param limit 限制数量，默认10
     * @return 最近申请列表
     */
    @GetMapping("/recent")
    public ResponseEntity<Map<String, Object>> getRecentApplications(@RequestParam(defaultValue = "10") int limit) {
        List<Application> applications = applicationService.getRecentApplications(limit);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "查询成功");
        response.put("data", applications.stream().map(this::convertToResponse).collect(java.util.stream.Collectors.toList()));
        return ResponseEntity.ok(response);
    }

    /**
     * 将Application实体转换为响应对象
     *
     * @param application 申请实体
     * @return 响应对象
     */
    private Map<String, Object> convertToResponse(Application application) {
        Map<String, Object> response = new HashMap<>();
        response.put("id", application.getId());
        response.put("phoneNumber", application.getPhoneNumber());
        response.put("status", application.getStatus());
        response.put("statusText", getStatusText(Application.Status.valueOf(application.getStatus())));
        response.put("applyTime", application.getApplyTime());
        response.put("reviewTime", application.getReviewTime());
        response.put("reviewer", application.getReviewer());
        response.put("remark", application.getRemark());
        
        // 添加申请名称和描述信息（使用默认值）
        response.put("name", "API Key申请 #" + application.getId());
        response.put("description", application.getRemark() != null && !application.getRemark().trim().isEmpty() ? application.getRemark() : "API Key申请");
        
        // 添加API Key信息（如果已通过审核，需要从ApiKey表查询）
        response.put("apiKey", application.isApproved() ? "已生成" : null);
        
        // 不返回敏感信息
        // response.put("verifyPassword", application.getVerifyPassword());
        // response.put("fingerprint", application.getFingerprint());
        
        return response;
    }

    /**
     * 获取状态文本
     *
     * @param status 状态
     * @return 状态文本
     */
    private String getStatusText(Application.Status status) {
        switch (status) {
            case PENDING:
                return "待审核";
            case APPROVED:
                return "已通过";
            case REJECTED:
                return "已拒绝";
            default:
                return "未知状态";
        }
    }

    /**
     * 申请请求对象
     */
    public static class ApplicationRequest {
        private String phoneNumber;
        private String verifyPassword;
        private String fingerprint;
        private String remark;

        // Getters and Setters
        public String getPhoneNumber() {
            return phoneNumber;
        }

        public void setPhoneNumber(String phoneNumber) {
            this.phoneNumber = phoneNumber;
        }

        public String getVerifyPassword() {
            return verifyPassword;
        }

        public void setVerifyPassword(String verifyPassword) {
            this.verifyPassword = verifyPassword;
        }

        public String getFingerprint() {
            return fingerprint;
        }

        public void setFingerprint(String fingerprint) {
            this.fingerprint = fingerprint;
        }

        public String getRemark() {
            return remark;
        }

        public void setRemark(String remark) {
            this.remark = remark;
        }
    }

    /**
     * 查询请求对象
     */
    public static class QueryRequest {
        private String phoneNumber;
        private String verifyPassword;
        private String fingerprint;

        // Getters and Setters
        public String getPhoneNumber() {
            return phoneNumber;
        }

        public void setPhoneNumber(String phoneNumber) {
            this.phoneNumber = phoneNumber;
        }

        public String getVerifyPassword() {
            return verifyPassword;
        }

        public void setVerifyPassword(String verifyPassword) {
            this.verifyPassword = verifyPassword;
        }

        public String getFingerprint() {
            return fingerprint;
        }

        public void setFingerprint(String fingerprint) {
            this.fingerprint = fingerprint;
        }
    }
}